package com.example.sunjian.myapplication.fragment;

import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.example.sunjian.myapplication.R;

import java.util.List;

/**
 * 作者：sunjian on 16/6/7 15:32
 * 邮箱：sunjian@cyhz.com
 */
public class FragmentTestActivity extends FragmentActivity implements View.OnClickListener{


    private Button btn1,btn2;
    private FrameLayout mFrag;
    private Fragment fragment1,fragment2;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main_layout);
        btn1 = (Button)findViewById(R.id.btn_1);
        btn2=(Button)findViewById(R.id.btn_2);
//        mFrag=(FrameLayout)findViewById(R.id.container);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        fragment1 = new Fragment_1();
        fragment2 = new Fragment_2();
        addContent(getSupportFragmentManager(),fragment1,R.id.container);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){

            case R.id.btn_1:
                addContent(getSupportFragmentManager(),new Fragment_1(),R.id.container);

                break;

            case R.id.btn_2:
                addContent(getSupportFragmentManager(),new Fragment_1(),R.id.container);

                break;
        }

    }


    public final void addContent(FragmentManager manager,
                                 Fragment fragment, int contentId) {
        FragmentTransaction transaction = manager.beginTransaction();
        List<Fragment> fragments = manager.getFragments();
        if (fragments == null) {
            transaction.add(contentId, fragment);
        } else {
            for (Fragment fragment2 : fragments) {
                transaction.hide(fragment2);
            }
            if (fragments.contains(fragment)) {
                transaction.show(fragment);
                Log.d("sj", "------ transaction.show(fragment);------");
            } else {
                transaction.add(contentId, fragment);
                Log.d("sj", "------transaction.add(contentId, fragment);------");
            }
        }
//        transaction.replace(contentId,fragment);
        transaction.commit();
    }


}
